package com.chen.librarysystem.service.impl;

import com.chen.librarysystem.entry.Book;
import com.chen.librarysystem.log.LibraryLog;
import com.chen.librarysystem.mapper.FileMapper;
import com.chen.librarysystem.mapper.impl.FileMapperImpl;
import com.chen.librarysystem.service.BookService;
import com.chen.util.LocalDateTimeUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

public class BookServiceImpl implements BookService {
    private final Map<String, Book> bookMap;
    private final FileMapper fileMapper = new FileMapperImpl();

    public BookServiceImpl() {
        // 将 loadBookData() 返回的 Map 包装成可变的 HashMap
        bookMap = new HashMap<>(fileMapper.loadBookData());
    }

    @Override
    public boolean addBook(Book book) {
        if (bookMap.containsKey(book.getTitle())) {
            LibraryLog.log(Level.WARNING, "图书已存在:" + book.getTitle());
            return false;
        }
        bookMap.put(book.getTitle(), book);
        fileMapper.saveBookData(bookMap);
        LibraryLog.log(Level.FINE, "添加图书成功:" + book.getTitle());
        return true;
    }

    @Override
    public boolean removeBookByTitle(String title) {
        if (!bookMap.containsKey(title)) {
            LibraryLog.log(Level.WARNING, "未找到该图书:" + title);
            return false;
        }
        if (bookMap.get(title).isBorrowed()) {
            LibraryLog.log(Level.WARNING, "图书已借出,无法删除:" + title);
            return false;
        }
        Book remove = bookMap.remove(title);
        fileMapper.saveBookData(bookMap);
        LibraryLog.log(Level.FINE, "删除图书成功:" + remove.getTitle());
        return true;
    }

    @Override
    public boolean updateBook(String title, Book book) {
        if (bookMap.containsKey(title)) {
            if (bookMap.get(title).isBorrowed()) {
                System.out.println("图书已借出,无法修改!");
                LibraryLog.log(Level.WARNING, "图书已借出,无法修改:" + title);
                return false;
            }
            Book book1 = bookMap.get(title);
            book1.setAuthor(book.getAuthor());
            book1.setIsbn(book.getIsbn());
            bookMap.put(title, book1);
            fileMapper.saveBookData(bookMap);
            LibraryLog.log(Level.FINE, "修改图书成功:" + book.getTitle());
            return true;
        }
        LibraryLog.log(Level.WARNING, "图书不存在:" + book.getTitle());
        return false;
    }

    @Override
    public List<Book> getAllBorrowedBooks() {
        if (bookMap != null) {
            List<Book> list = bookMap.values().stream().filter(Book::isBorrowed).toList();
            if (list.isEmpty()) {
                LibraryLog.log(Level.WARNING, "没有借阅图书");
            } else {
                LibraryLog.log(Level.INFO, "获取所有被借阅图书");
            }
            return list;
        }
        LibraryLog.log(Level.WARNING, "图书列表为空");
        return List.of();
    }

    @Override
    public void borrowBook(String title, String userName) {
        if (!bookMap.containsKey(title)) {
            System.out.println("未找到该图书!");
            LibraryLog.log(Level.WARNING, "未找到该图书:" + title);
            return;
        }
        // 判断用户是否已经借过五本图书
        if (getBorrowedBooksByUser(userName).size() > 5) {
            System.out.println("借阅数量已达上限!");
            LibraryLog.log(Level.WARNING, "借阅数量已达上限:" + title);
            return;
        }
        Book book = bookMap.get(title);
        if (!book.isBorrowed()) {
            book.setBorrowed(true);
            book.setBorrowDate(LocalDateTimeUtil.getDate());
            book.setBorrower(userName);
            book.setReturner(null);
            book.setReturnDate(null);
            System.out.println("借阅成功!");
            LibraryLog.log(Level.FINE, "借阅图书成功:" + title + ",借阅人:" + userName);
            bookMap.put(title, book);
            fileMapper.saveBookData(bookMap);
            return;
        }
        System.out.println("图书已借出!");
        LibraryLog.log(Level.WARNING, "图书已借出:" + title);
    }

    @Override
    public void returnBook(String title, String userName) {
        if (!bookMap.containsKey(title)) {
            System.out.println("未找到该图书!");
            LibraryLog.log(Level.WARNING, "未找到该图书:" + title);
            return;
        }
        Book book = bookMap.get(title);
        if (book.isBorrowed() && book.getBorrower().equals(userName)) {
            book.setBorrowed(false);
            book.setReturnDate(LocalDateTimeUtil.getDate());
            book.setReturner(userName);
            bookMap.put(title, book);
            fileMapper.saveBookData(bookMap);
            System.out.println("归还成功!");
            LibraryLog.log(Level.FINE, "归还图书成功:" + title + ",归还人:" + userName);
            return;
        }
        System.out.println("图书未借出或借阅者不匹配!");
    }

    @Override
    public List<Book> getBorrowedBooksByUser(String userName) {
        return getAllBorrowedBooks().stream()
                .filter(book -> book.getBorrower().equals(userName)).toList();
    }

    @Override
    public List<Book> getBookByTitleOrAuthor(String title) {
        List<Book> bookList = new ArrayList<>();
        if (bookMap.isEmpty()) {
            LibraryLog.log(Level.INFO, "暂无数据！");
            return null;
        }
        for (Book book : bookMap.values()) {
            if (book.getTitle().contains(title) || book.getAuthor().contains(title)) {
                bookList.add(book);
            }
        }
        return bookList;
    }

    @Override
    public List<Book> getAllBooks() {
        if (bookMap.isEmpty()) {
            LibraryLog.log(Level.INFO, "暂无数据");
            return List.of();
        }
        LibraryLog.log(Level.INFO, "获取所有图书");
        return bookMap.values().stream().toList();
    }
}
